import { defineStore } from "pinia";
import { getcartlist, delcartlist, putcartnum } from "@/api/index.js";
import { showSuccessToast, showFailToast } from "vant";
export const useCart = defineStore("CartStore", {
  state: () => {
    return {
      CartList: [],
    };
  },
  actions: {
    changeCartList(data) {
        this.CartList = data.map((item) => {
          item.checked = true;
          return item;
        });
      
      // if (this.CartList.length==0) {
      //   this.CartList = data.map((item) => {
      //     item.checked = true;
      //     return item;
      //   });
      // }else{
      //   for (let i = 0; i < data.length; i++) {
      //     data[i].checked = this.CartList[i].checked;
      //   }
      //   this.CartList = data;
      // }
    },
    //获取购物车数据
    getmycartlist() {
      getcartlist().then((res) => {
        this.changeCartList(res.data || []);
      });
    },
    //删除购物车数据
    delmycartlist(id) {
      delcartlist(id).then((res) => {
        if (res.resultCode == 200) {
          showSuccessToast("删除成功");
          this.getmycartlist();
        }
      });
    },
    //购物车步进器
    putmycartnum(cartItemId, goodsCount) {
      putcartnum(cartItemId, goodsCount).then((res) => {
        if (res.resultCode == 200) {
          // this.getmycartlist()
          getcartlist().then((res) => {
            for (let i = 0; i <res.data.length; i++) {
              res.data[i].checked = this.CartList[i].checked;
            }
            this.CartList = res.data;
          });
        }
      });
    },
  },
  getters: {
    cartNum() {
      return this.CartList.reduce((prev, next) => {
        return prev + next.goodsCount;
      }, 0);
    },
  },
});
